package com.lce.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lce.beans.Attendance;
import com.lce.beans.Chart;
import com.lce.beans.Leave;
import com.lce.beans.TimeTable;
import com.lce.beans.User;
import com.lce.beans.UserUid;
import com.lce.service.UserService;
import com.lce.service.UserSigin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    private UserService userService;
    private UserSigin userSigin;


    public UserSigin getUserSigin() {
        return userSigin;
    }

    public UserService getUserService() {
        return userService;
    }

    @Resource
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Resource
    public void setUserSigin(UserSigin userSigin) {
        this.userSigin = userSigin;
    }

    //注册
    @RequestMapping("/add")
    public String addUser(User user) {
        //将对象传递至service层
        userService.addUser(user);
        //返回页面 转发或者重定向
        return "index";

    }

    //插入打卡记录
    public void sigin() {
        //只要服务启动  就会判断一次今天的所有成员签到表是否已经生成
        //先获取今天的时间字符串格式进行比较
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        int i = userSigin.getToday(format);
        if (i != 0) {
            //有当日的打卡表  不用新插入数据

        } else {
            //当日数据暂无 插入所有员工当日打卡表
            //先获取所有员工id
            List<User> users = userService.getAllUser();
            System.out.println("检查查询到的员工编号" + users);
            List<UserUid> userList = new ArrayList<>();
            for (int i1 = 0; i1 < users.size(); i1++) {
                UserUid userUid = new UserUid();
                System.out.println("获得到的用户编号" + users.get(i1).getUid());
                userUid.setUid(users.get(i1).getUid());
                userUid.setAttendancedate(format);
                userList.add(userUid);
            }
            System.out.println("检查检查" + userList);
            System.out.println(userList);
            //把员工id以及日期写入记录表供员工打卡使用
            userSigin.addAllRecord(userList);

        }
    }

    //登录
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest req) {
        sigin();
        System.out.println(user);
        User user1 = userService.login(user);
        System.out.println("检查登录账号" + user1);
        if (user1 != null) {
            System.out.println("登陆成功");
            req.getSession().setAttribute("user", user1);
            if (user1.getRid() == 3) {
                //ceo
                System.out.println("进入ceo界面");
                return "redirect:ceomain.jsp";
            } else if (user1.getRid() == 2) {
                //经理
                return "redirect:managermain.jsp";
            } else {
                //员工
                return "redirect:main.jsp";
            }

        } else {
            System.out.println("登陆失败");
            return "login";
        }
    }


    //签到
    @RequestMapping("/signin")
    @ResponseBody
    public Object sin(@RequestParam("result") String result, HttpServletRequest req) {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        System.out.println("检查获取的session数据" + user);
        System.out.println("接收打卡类型正常？迟到？1:按时签到2:迟到签到3:签退4:非签退时间 参数" + result);
        //接收到的参数查询该参数对应什么打卡类型
        String result1 = userSigin.getResult(Integer.parseInt(result));
        System.out.println("检查result" + result1);
        //把得到的打卡类型以及相应的打卡时间加入数据库
        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String day = sdf.format(date);
        //如果后端传输的是1  正常签到   2  迟到签到   3   签退
        if (Integer.parseInt(result) == 1 | Integer.parseInt(result) == 2) {
            //签到
            //获取当前时间转换字符串格式
            Date date1 = new Date();
            SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String format = sft.format(date1);
            Map map = new HashMap();
            map.put("user", user);
            map.put("result1", result1);
            map.put("day", day);
            map.put("time", format);
            userSigin.addAttendance(map);
        } else {
            Map map = new HashMap();
            map.put("user", user);
            map.put("result1", result1);
            map.put("day", day);
            Date date1 = new Date();
            SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String format = sft.format(date1);
            map.put("time", format);
            userSigin.updateAttendance(map);
        }
        return 1;
    }

    //签到
    @RequestMapping("/gettime")
    @ResponseBody
    public int gettime(HttpServletRequest request) throws Exception {
        System.out.println("==================");
        TimeTable timeTable = userSigin.getTimeTable(3);
        System.out.println("检查查询到的timetable" + timeTable);
//      开始打卡时间
        String str = timeTable.getOnworktime();
        String[] parts = str.split(":");
        String HH = parts[0];
        String mm = parts[1];
        System.out.println(HH + "=======" + mm);
//      更新年月日转字符串拼接固定打卡时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd" + " " + HH + ":" + mm);
        Date date = new Date();
        String day = sdf.format(date);
//        打卡时间字符串转为时间格式
        SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date time = sft.parse(day);
        System.out.println("开始打卡时间" + time);
//      上班时开始间
        String str1 = timeTable.getYonworktime();
        String[] parts1 = str1.split(":");
        String HH1 = parts1[0];
        String mm1 = parts1[1];
        System.out.println(HH1 + "=======" + mm1);
//      更新年月日转字符串拼接固定打卡时间
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd" + " " + HH1 + ":" + mm1);
        Date date1 = new Date();
        String day1 = sdf1.format(date1);
//        打卡时间字符串转为时间格式
        SimpleDateFormat sft1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date time1 = sft1.parse(day1);
        System.out.println("开始上班时间" + time1);
//      结束打卡时间
        String str2 = timeTable.getEndonworktime();
        String[] parts2 = str2.split(":");
        String HH2 = parts2[0];
        String mm2 = parts2[1];
        System.out.println(HH2 + "=======" + mm2);
//      更新年月日转字符串拼接固定打卡时间
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd" + " " + HH2 + ":" + mm2);
        Date date2 = new Date();
        String day2 = sdf2.format(date2);
//      打卡时间字符串转为时间格式
        SimpleDateFormat sft2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date time2 = sft2.parse(day2);
        System.out.println("结束打卡时间" + time2);
//      签退开始时间
        String str3 = timeTable.getOffworktime();
        String[] parts3 = str3.split(":");
        String HH3 = parts3[0];
        String mm3 = parts3[1];
        System.out.println(HH3 + "=======" + mm3);
//      更新年月日转字符串拼接固定打卡时间
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd" + " " + HH3 + ":" + mm3);
        Date date3 = new Date();
        String day3 = sdf3.format(date3);
//      打卡时间字符串转为时间格式
        SimpleDateFormat sft3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date time3 = sft3.parse(day3);
        System.out.println("签退开始时间" + time3);
//      签退结束时间
        String str4 = timeTable.getEndoffworktime();
        String[] parts4 = str4.split(":");
        String HH4 = parts4[0];
        String mm4 = parts4[1];
        System.out.println(HH4 + "=======" + mm4);
//      更新年月日转字符串拼接固定打卡时间
        SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd" + " " + HH4 + ":" + mm4);
        Date date4 = new Date();
        String day4 = sdf4.format(date4);
//      打卡时间字符串转为时间格式
        SimpleDateFormat sft4 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date time4 = sft4.parse(day4);
//      格式化员工打卡时间
        SimpleDateFormat stf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String format = stf.format(date);
//        员工打卡时间字符串转日期
        Date realtime = stf.parse(format);
        System.out.println("张三打卡时间" + realtime);
//      "开始打卡时间" + time    "开始上班时间" + time1    "结束打卡时间" + time2  "张三打卡时间" + realtime
        boolean after = realtime.after(time);
        boolean before = realtime.before(time1);
        boolean after1 = realtime.after(time1);
        boolean before1 = realtime.before(time2);
        boolean after2 = realtime.after(time3);
        boolean before2 = realtime.before(time4);
//      判断是否已经签退
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        System.out.println("检查获取的session数据" + user);
        SimpleDateFormat swf = new SimpleDateFormat("yyyy-MM-dd");
        Date dated = new Date();
        String dayd = swf.format(dated);
        Map map1 = new HashMap();
        map1.put("uid", user.getUid());
        map1.put("day", dayd);
        int a = userSigin.getAttendance(map1);
        int b = userSigin.getBack(map1);
        //比较打卡时间判断是否可以打卡
        if (after & before & a == 0) {
            return 1;
        } else if (after1 & before1 & a == 0) {
            return 2;
        } else if (after & before1 & a != 0) {
            return 4;
        } else if (after2 & before2 & b == 0) {
            return 3;
        } else if (after2 & before2 & b != 0) {
            return 4;
        } else {
            return 5;
        }
    }
    //查看个人信息
    @RequestMapping("/getUser")
    public String getUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user1 = (User) session.getAttribute("user");
        //个人信息查询
        User user = userService.getUser(user1.getUid());
        System.out.println("个人信息" + user);
        System.out.println("个人信息" + user.getRole());
        System.out.println("个人信息" + user.getDept());
        request.setAttribute("user", user);
        return "getUser";
    }
    //查询打卡记录
    @RequestMapping("/getRecord")
    @ResponseBody
    public Object getRecord(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user1 = (User) session.getAttribute("user");
        int uid = user1.getUid();
        List<Attendance> attendances = userSigin.getRecord(uid);
        System.out.println(attendances);
        return attendances;
    }
    //查询请假记录
    @RequestMapping("/getLeave")
    @ResponseBody
    public Object getLeave(HttpServletRequest request) {
        System.out.println("第1行");
        HttpSession session = request.getSession();
        System.out.println("第2行");
        User user1 = (User) session.getAttribute("user");
        System.out.println("第3行");
        int uid = user1.getUid();
        System.out.println("第4行");
        List<Leave> leaves = userSigin.getLeave(uid);
        System.out.println(leaves);
        System.out.println("第5行");
        for (int i = 0; i < leaves.size(); i++) {
            System.out.println("检查" + leaves.get(i));
            System.out.println("检查" + leaves.get(i).getUser());
            System.out.println("检查" + leaves.get(i).getLeaveType());
        }
        return leaves;
    }
    @RequestMapping("/updateUser")
    public void updateUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user1 = (User) session.getAttribute("user");
        String uname = request.getParameter("uname");
        String sex = request.getParameter("sex");
        String image = request.getParameter("image");
        int age = Integer.parseInt(request.getParameter("age"));
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String birthday = request.getParameter("birthday");
        String address = request.getParameter("address");
        String email = request.getParameter("email");
        User user = new User(user1.getUid(), uname, password, sex, age, birthday, email, phone, image, address);
        System.out.println("检查一下" + user);
        userService.updateUser(user);
    }
    @RequestMapping("/userAddLeave")
    public String addLeave(HttpServletRequest request) {
        Leave leave = new Leave();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        leave.setUid(user.getUid());
        String leavetypeid = request.getParameter("leavetypeid");
        System.out.println(leavetypeid);
        String starttime = request.getParameter("starttime");
        System.out.println(starttime);
        String endtime = request.getParameter("endtime");
        System.out.println(endtime);
        String total = request.getParameter("total");
        System.out.println(total);
        leave.setTypeId(Integer.parseInt(leavetypeid));
        leave.setStartTime(starttime);
        leave.setEndTime(endtime);
        leave.setTotal(Integer.parseInt(total));
        leave.setStatus("未审批");
        //审批人id查询 员工请假经理批 经理请假ceo批
        int ApprovalId = userService.getApprovalId(user.getDid());
        leave.setApprovalId(String.valueOf(ApprovalId));
        Date date = new Date();
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
        String applyTime = sm.format(date);
        System.out.println(applyTime);
        leave.setApplyTime(applyTime);
        userService.addLeave(leave);
        return "getLeave";
    }
    @RequestMapping("/getAge")
    @ResponseBody
    public String getNumber() throws JsonProcessingException {
        Map R = new HashMap<>();
        List<Chart> charts=userService.getChart();
        System.out.println(charts);
        ArrayList<String> xAxis = new ArrayList<>();
        ArrayList<Integer> seriesData = new ArrayList<>();
        for (Chart chart : charts) {
            xAxis.add(chart.getName());
            seriesData.add(chart.getNumber());
        }
        R.put("xAxis",xAxis);
        R.put("seriesData",seriesData);
        System.out.println(R);
        String string = JSON.toJSONString(R);
        return string;
    }
}
